﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Approval;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Approval
{
    /// <summary>
    /// 查询请假列表
    /// </summary>
    public class QueryApprovalCommandHandler : IRequestHandler<QueryApprovalCommand, APIResult<APIPaging<LeaveApplication>>>
    {
        private readonly IBaseRepository<LeaveApplication> leaveappRep;

        public QueryApprovalCommandHandler(IBaseRepository<LeaveApplication> leaveappRep)
        {
            this.leaveappRep = leaveappRep;
        }

        public async Task<APIResult<APIPaging<LeaveApplication>>> Handle(QueryApprovalCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<LeaveApplication>> result = new APIResult<APIPaging<LeaveApplication>>();

            // 获取当前用户信息

            var isLeader = request.DepartmentHead;          // 假设有IsLeader属性


            // 构建基础查询
            var list = leaveappRep.GetAll().Result.Where(x => x.IsDel == false);

            // 动态过滤条件
            if (isLeader == 1)
            {
                // 领导：查询本部门所有记录
                list = list.Where(x => x.DepartMentid == request.DepartmentId);
            }
            else if (isLeader == 0)
            {
                // 普通用户：仅查询自己创建的记录
                list = list.Where(x => x.CreateName == request.NickName);
            }
            else
            {
                list = list;
            }
            var recordCount = list.Count();
            var pageCount = (int)Math.Ceiling(recordCount * 1.0 / request.PageSize);
            var pageList = list.OrderByDescending(x=>x.LeaveId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            APIPaging<LeaveApplication> paging = new APIPaging<LeaveApplication>();
            paging.RecordCount = recordCount;
            paging.PageCount = pageCount;
            paging.Items = pageList.ToList();
            result.Code = APIEnum.查询成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.data = paging;
            return await Task.FromResult(result);
        }
    }
}
